<?php
/**
 * Created by PhpStorm.
 * User: zhaoyang   
 * Date: 2017/07/21
 * Time: 下午4:44
 */
class ScsUserServiceCardController extends BaseController {
    /**
     * @Author:      zhaoyang
     * @DateTime:  2017-07-27 
     * @Description: 查找当前门店的产品信息
     */
    public function packList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'uid' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            
            $uid = Input::get('uid');  
            if(is_null($uid)){$response = Lang::get("scs_error.user_id_error_40005"); break;}
            
            $place = Input::get('place',2);  //工作地点：1上门 2到店(默认)
            $record = Input::get('record',1); //是否有购买记录：1有(默认) 2没有 
            $lose = Input::get('lose',1); //是否过滤剩余次数为0的值 1过滤 0不过滤
            $page = Input::get('page',1);
            $page_size = Input::get('page_size',25);
            //先调用产品接口，查找当前门店产品id的集合。 
            if ($record == 1) {
                $ids = ServiceCardBasePack::shopPackIds(null,$uid);
                $sql_struct = "select %s from product_package a 
                                left join service_card_detail_pack b on a.id=b.pack_id
                                where b.id in ($ids) ";
                $sql_struct1 = "select %s from product_package a 
                                    left join service_card_detail_pack b on a.id=b.pack_id 
                                    left join service_card_detail c on b.service_card_detail_id=c.id 
                                    left join  service_card_base d on b.service_card_base_id=d.id 
                                    where b.id in ($ids) and (c.status=0 or d.user_status=0 or c.end_date < '" . date('Y-m-d H:i:s',time()) . "')";
                $sql_tail = "";
                $ser_arr  = [];
                if (!empty($place)) { $sql_tail .= " and a.place=? ";$ser_arr[] = $place;}

                $sql_tail .= "GROUP BY a.id";
                $sql_struct .= $sql_tail;
                $sql_struct1 .= $sql_tail;
                $count_sql = sprintf($sql_struct," a.id, number-curr_number use_number");
                $count_sql = "select count(id) count from ($count_sql) a"; //因为group_by了 所以这样使用
                $count = DB::select($count_sql,$ser_arr); 
                $count = $count[0]->count;

                $sql = sprintf($sql_struct," a.id,a.`name`,a.place,sum(b.number) number,sum(curr_number) curr_number , number-curr_number use_number ");
                $sql .= " limit ".$page_size*($page-1).",".$page_size;
                $list = DB::select($sql,$ser_arr);
                
                $sql1 = sprintf($sql_struct1," a.id,a.`name`,a.place,sum(b.number) as number,sum(b.curr_number) as curr_number , (number-curr_number) as use_number ");
                $list1 = DB::select($sql1,$ser_arr);
                
                foreach($list as $key=>&$li){
                    foreach ($list1 as $li1){
                        if($li->id == $li1->id) {
                            $li->curr_number = $li->curr_number - $li1->curr_number;
                        }
                    }
                    if ($lose == '1' && $li->curr_number == 0) {unset($list[$key]);}
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['list'=>$list,'record' => $record,"count"=>$count]);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "packList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zhaoyang
     * @DateTime:  2017-07-27 
     * @Description: 当前门店包含当前产品的套餐卡的信息
     */
    public function packToServiceCard(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pack_id'=> 'required',
                'uid' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            
            $pack_id = Input::get('pack_id');  //pack_id 产品id
            if(is_null($pack_id)){$response = Lang::get("scs_error.pack_id_error_40005"); break;}
            
            $uid = Input::get('uid');
            if(is_null($uid)){$response = Lang::get("scs_error.user_id_error_40005"); break;}
            
            $page = Input::get('page',1);
            $page_size = 15;

            //先调用产品接口，查找当前门店产品id的集合。 
            $ids = ServiceCardBasePack::shopPackIds($sc_user->shop_id,$uid,$pack_id);

            $sql_struct = "select %s "
                    . " from service_card_detail a "
                    . "left join service_card_detail_pack as b on b.service_card_detail_id = a.id "
                    . "left join  service_card_base c on a.service_card_base_id=c.id "
                    . "where b.id in ($ids) and a.status<>1";
            $count = DB::select(sprintf($sql_struct," count(a.id) count"));
            
            $sql = sprintf($sql_struct,"a.id,c.id as bid,c.name,a.status,c.user_status,b.number,b.curr_number,a.end_date");
            $sql .= " limit ".$page_size*($page-1).",".$page_size;
            $list = DB::select($sql);
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("list"=>$list,"count"=>$count[0]->count));
        } while (false);
         Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "packToServiceCard", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zhaoyang
     * @DateTime:  2017-07-27 
     * @Description: 套餐卡使用记录
     */
    public function ServiceCardUseRecord(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'scd_id'=> 'required', //service_card_detail_id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $scd_id= Input::get('scd_id');  //pack_id 产品id
            if(is_null($scd_id)){$response = Lang::get("scs_error.scd_id_error_40005"); break;}
            $list = ServiceCardConsumption::select('order_id','type','status','updated_at')->where('service_card_detail_id',$scd_id)->where('status', '<>', 2)->get();
            if (!empty($list)) {
                foreach ($list as $v) {
                    $table = $v->type == 1 ? 'car_wash_order' : 'orders';
                    $order_sql = "select b.shop_id,c.name from $table b left join maintenance_shops c on b.shop_id=c.id where b.order_id = $v->order_id";
                    $order_info = DB::select($order_sql);
                    $v->shop_id = $order_info[0]->shop_id ;
                    $v->name = $order_info[0]->name ;
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("list"=>$list));
        } while (false);
         Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "ServiceCardUseRecord", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zhaoyang
     * @DateTime:  2017-07-27 
     * @Description: 关闭套餐卡列表
     */
    public function userServiceCardList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'uid'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $uid= Input::get('uid');  //pack_id 产品id
            if(is_null($uid)){$response = Lang::get("scs_error.user_error_40005"); break;}

            $page = Input::get('page',1);
            $page_size = 15;
            
            $sql_struct = "select  %s from service_card_detail a
                    left join service_card_base b on a.service_card_base_id=b.id 
                    where a.user_id = ? and a.status<>1";

            $count = DB::select(sprintf($sql_struct," count(a.id) count"),[$uid]);
            
            $sql = sprintf($sql_struct,"a.id,b.id as bid,b.name,a.status,b.user_status,a.end_date");
            $sql .= " limit ".$page_size*($page-1).",".$page_size;
            $list = DB::select($sql,[$uid]);
            
            if (!empty($list)) {
            foreach ($list as $v) {
                $scdPackInfo = ServiceCardBasePack::scdPackInfo($v->id); //汇总当前套餐卡下的产品
                foreach ($scdPackInfo as $pack_value) {
                    if (!isset($v->all_amount)) $v->all_amount = 0;
                    $v->all_amount += $pack_value->curr_number * $pack_value->amount;
                    if (!isset($v->number)) $v->number = 0;
                    $v->number += $pack_value->number;
                }
            } 
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=> $list,"count"=>$count[0]->count] );
        } while (false);
         Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "userServiceCardList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zhaoyang
     * @DateTime:  2017-07-27 
     * @Description: 修改套餐卡状态
     */
    public function updateStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'scd_id'=> 'required',
                'status'=> 'required', //最终修改结果
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user))break;

            $scd_id = Input::get('scd_id');  //pack_id 产品id
            $status = Input::get('status');    
            if($status==2){//暂时不允许开启套餐卡
                $response = Lang::get("scs_error.service_card_car_error_95023");
                break;
            }  
            $dln=ServiceCardDetail::where('id',$scd_id)->first();
            $dln->status = $status;
            $dln->save();   //修改

            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("scd_id"=>$dln->id));
        } while (false);
         Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "updateStatus", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      zy
     * @DateTime:    2017-9-05 17:23:45
     * @Description: 用于展示 绑定车辆
     */
    public function userBindCarsList()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
        $where = array();
        $user_id = Input::get('user_id');
        $page_size = Input::get('page_size',25);
        $page = Input::get('page',1);
        $start = ($page-1)*$page_size;
        $user = Users::find($user_id);
        $count = ServiceCardCar::where('user_id',$user_id)->orderBy('created_at','desc')->count();
        $cars = ServiceCardCar::where('user_id',$user_id)->orderBy('created_at','desc')->skip($start)->take($page_size)->orderBy('status', 'desc')->get();
        $source = ServiceCardCar::$source;
        foreach($cars as &$ca){
            $ca->status = $ca->status == 0 ? '关闭' : '开启';
            $ca->source = $source[$ca->source];
            $ca->unbund_source = $source[$ca->unbund_source];
            $ca->unbund_at = $ca->unbund_at == '0000-00-00 00:00:00' ? '' : $ca->unbund_at;
        }
        $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("list"=>$cars, 'user_id'=>$user_id,'user'=>$user,'count'=>$count));
    }while (false);
        Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "userBindCarsList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zh
     * @DateTime:    2015-10-20 17:23:45
     * @Description: 解除绑定
     */
    public function unbindCar()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $user_id = Input::get('user_id');
            $id = Input::get('id');
            $dln = ServiceCardCar::where('id',$id)->where('user_id',$user_id)->first();
            if($dln) {
                $dln->status = 0;
                $dln->unbund_at = date("Y-m-d H:i:s",time());
                $dln->unbund_source = 4;
                $dln->save();   //修改
                $result = array(
                    'status' => 0,
                    'msg' => '操作成功',
                );
            }else{
                $result = array(
                    'status' => -1,
                    'msg' => '操作失败',
                );
            }
        $response = array('code' => 0, 'msg' => 'ok', 'result' =>$result);
    }while (false);
        Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "unbindCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zh
     * @DateTime:    2015-10-20 17:23:45
     * @Description: 绑定车牌
     */
    public function storeCar()
    {
        
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'car_no' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

        $user_id = Input::get('user_id');
        $car_no = Input::get('car_no');

        if(!$car_no){$response = Lang::get("scs_error.service_card_car_error_95020"); break;}
        
        $service_card = ServiceCard::where('user_id',$user_id)->first();
        if(empty($service_card)){
            $service_card = new ServiceCard();
            $service_card->account_no = date("YmdHis",time());
            $service_card->user_id = $user_id;
            if(!$service_card->save()){
                $response = Lang::get("scs_error.service_card_car_error_95018"); break;
            }

        }
        
        $repeat = ServiceCardCar::where('user_id',$user_id)->where('account_no',$service_card->account_no)->where('car_no',$car_no)->where('status',1)->first();
        if(!empty($repeat)){$response = Lang::get("scs_error.service_card_car_error_95022"); break;}
        
        // $count = ServiceCardCar::where('user_id',$user_id)->where('account_no',$service_card->account_no)->where('status',1)->count();
        // if($count > 4){
        //     $response = Lang::get("scs_error.service_card_car_error_95017"); break;
        // }
        $service_card_car = new ServiceCardCar();
        $service_card_car->user_id =$user_id;
        $service_card_car->account_no = $service_card->account_no;
        $service_card_car->car_no = $car_no;
        $service_card_car->status = 1;
        $service_card_car->source = 4;
        if(!$service_card_car->save()){
            $response = Lang::get("scs_error.service_card_car_error_95019"); break;
        }
        $response = array('code' => 0, 'msg' => 'ok', 'result' =>array('status' => 0,'msg' => '操作成功'));
    }while (false);
        Log::info("info", array("system" => "scs" ,"model" => "UserServiceCard", "event" => "storeCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}


